const { fileUploadError, unSupportedFileType, publishGoodsError, invalidGoodsID } = require("../constant/error.type")
const { createGoods, updateGoodsInfoById, removeGoodsInfoByID, restoreGoodsInfoByID, getGoodsList } = require("../service/goods.service")

class GoodsController {
  async upload (ctx, next) {
    // koabody会将上传的文件放置在ctx.request.files
    const { file } = ctx.request.files
    const fileTypes = ['image/jpeg', 'image/png']
    if (file) {
      if (!fileTypes.includes(file.mimetype)) {
        return ctx.app.emit('error', unSupportedFileType, ctx)
      }
      ctx.body = {
        message: '商品图片上传成功',
        code: 0,
        result: {
          goods_img: file.newFilename
        }
      }
    } else {
      console.error(fileUploadError.message)
      return ctx.app.emit('error', fileUploadError, ctx)
    }
  }
  /**创建商品 */
  async create (ctx) {
    // 调用创建商品方法
    try {
      // 通过剩余参数剔除createdAt，updatedAt
      const { createdAt, updatedAt, ...res } = await createGoods(ctx.request.body)
      ctx.body = {
        code: 0,
        message: '发布商品成功',
        result: res
      }
    } catch (error) {
      return ctx.app.emit('error', publishGoodsError, ctx)
    }
  }
  /**更新商品 */
  async update (ctx) {
    // 获取商品id
    const { id } = ctx.params

    try {
      const res = await updateGoodsInfoById(id, ctx.request.body)
      if (res) {
        ctx.body = {
          code: 0,
          message: '修改商品成功',
          result: '',
        }
      } else {
        console.log(invalidGoodsID.message);
        return ctx.app.emit('error', invalidGoodsID, ctx)
      }
    } catch (error) {
      console.error(err)
    }
  }
  /**下架商品 */
  async remove (ctx) {
    // 获取商品id
    const { id } = ctx.params
    try {
      const res = await removeGoodsInfoByID(id)
      if (res) {
        ctx.body = {
          code: 0,
          message: '下架商品成功',
          result: '',
        }
      } else {
        console.log(invalidGoodsID.message);
        return ctx.app.emit('error', invalidGoodsID, ctx)
      }
    } catch (error) {
      console.error(err)
    }
  }
  /**上架商品 */
  async restore (ctx) {
    // 获取商品id
    const { id } = ctx.params
    try {
      const res = await restoreGoodsInfoByID(id)
      if (res) {
        ctx.body = {
          code: 0,
          message: '上架商品成功',
          result: '',
        }
      } else {
        console.log(invalidGoodsID.message);
        return ctx.app.emit('error', invalidGoodsID, ctx)
      }
    } catch (error) {
      console.error(err)
    }
  }
  /**商品列表 */
  async findAll (ctx) {
    // 1.解析参数信息
    const { pageNum = 1, pageSize = 10 } = ctx.request.query
    // 2.查询数据库
    const res = await getGoodsList(pageNum, pageSize)
    ctx.body = {
      code: 0,
      message: '获取商品列表成功',
      result: res,
    }
  }
}
module.exports = new GoodsController()